package concurrentV;

public class TwoPrinterA_Z {
    static class PrintTask implements Runnable {
        private static final int TOTAL_LETTERS = 26;
        private static int currentLetter = 0; // 共享变量，用于标记当前打印到的字母索引
        private final Object lock;
        private final boolean isUpperCase;

        public PrintTask(Object lock, boolean isUpperCase) {
            this.lock = lock;
            this.isUpperCase = isUpperCase;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    // 如果已经打印完所有字母，则退出
                    if (currentLetter >= TOTAL_LETTERS) {
                        lock.notifyAll(); // 通知其他线程
                        break;
                    }

                    // 判断是否当前线程的打印时机
                    if ((currentLetter % 2 == 0) == isUpperCase) {
                        char letter = (char) ('A' + currentLetter);
                        if (!isUpperCase) {
                            letter = Character.toLowerCase(letter);
                        }
                        System.out.print(letter);

                        currentLetter++;
                        lock.notifyAll(); // 唤醒另一个线程
                    } else {
                        try {
                            lock.wait(); // 等待其他线程打印
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        Object lock = new Object();

        Thread t1 = new Thread(new PrintTask(lock, true));  // 打印大写字母
        Thread t2 = new Thread(new PrintTask(lock, false)); // 打印小写字母

        t1.start();
        t2.start();
    }

}
